package main

import (
	"golang.org/x/time/rate"
	"net/http"
)

var r = rate.NewLimiter(1, 5)

func MyLimit(next http.Handler) http.Handler {
	return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
		if r.Allow() {
			next.ServeHTTP(writer, request)
		} else {
			http.Error(writer, "too fast", http.StatusTooManyRequests)
			return
		}
	})
}
func main() {

	mux := http.NewServeMux()
	mux.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
		writer.Write([]byte("ok"))
	})
	http.ListenAndServe(":8081", MyLimit(mux))
}

/*func main2() {
	limiter := rate.NewLimiter(1, 5)

	ctx := context.Background()
	for {
		 //阻塞当前直到lim允许n个事件的发生。
		err := limiter.WaitN(ctx,2)
		if err!= nil {
			log.Fatal(err)
		}
		fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
		time.Sleep(time.Second)
	}
}*/
